package com.atguigu.flink.chapter05.transform;

import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/9/14 14:29
 */
public class Flink01_Map {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        
        DataStreamSource<Integer> stream = env.fromElements(1, 2, 3, 4, 5);
        
        /*stream
            .map( value -> value * value)
            .print();*/
    
        stream
            .map(new RichMapFunction<Integer, Integer>() {
            
                @Override
                public void open(Configuration parameters) throws Exception {
                    // 当程序启动的时候执行, 执行的次数与当前算子的并行度一致
                    System.out.println("Flink01_Map.open");
                    // 开辟资源: 建立到数据库的连接
                }
            
                @Override
                public Integer map(Integer value) throws Exception {
                    System.out.println("Flink01_Map.map");
                    return value;
                }
            
                @Override
                public void close() throws Exception {
                    // 当程序停止的时候执行的次数与当前算子的并行度一致
                    System.out.println("Flink01_Map.close");
                    // 关闭资源
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
